//
//  SettingsViewController.m
//  DaiShengInvest
//
//  Created by 张睿 on 2017/6/30.
//  Copyright © 2017年 davinci. All rights reserved.
//

#import "SettingsViewController.h"
#import "ServiceCenterTableViewCell.h"
#import "SettingsTableViewCell.h"
#import "UpdateNameViewController.h"
#import "UpdatePasswordViewController.h"
#import "UpdateEmailViewController.h"
#import "AppDelegate.h"
#import "BlackNavViewController.h"
#import "LoginViewController.h"

@interface SettingsViewController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate, UINavigationControllerDelegate>{
    
    UIImagePickerController *_imagePickerController;
    
}

@property (nonatomic, strong)SettingsTableViewCell * settingCell;

@property (nonatomic, strong)UIAlertController * alertVC;

@property (nonatomic, weak)UIImageView * backImageView;

@property (nonatomic, strong)UITableView * tableView;

@property (nonatomic, strong)UIButton * signOutButton;


@end

@implementation SettingsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _imagePickerController = [[UIImagePickerController alloc] init];
    _imagePickerController.delegate = self;
    _imagePickerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    _imagePickerController.allowsEditing = YES;
    
    
    [self setupNavBar];
    [self setupUI];
    [self setupAlertVC];
}

- (void)setupNavBar{
    
    self.title = @"设置";
    
    UIButton * backButton = [[UIButton alloc] init];
    
    backButton.frame = CGRectMake(15 * SCREENH6, 5 * SCREENH6, 12 * SCREENH6, 20 * SCREENH6);
    [backButton setImage:[UIImage imageNamed:@"1返回"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backToAccountView) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationItem.leftBarButtonItem = leftButton;
}



- (void)setupUI{
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIImageView * backImage = [[UIImageView alloc] init];
    
    backImage.image = [UIImage imageNamed:@"背景"];
    
    self.backImageView = backImage;
    
    [self.view addSubview:self.backImageView];
    
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64 * SCREENH6, SCREEN_WIDTH, 370 * SCREENH6)];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.bounces = NO;
    
    [self.tableView registerClass:[ServiceCenterTableViewCell class] forCellReuseIdentifier:@"serviceCenterCell"];
    
    [self.tableView registerClass:[SettingsTableViewCell class] forCellReuseIdentifier:@"SettingsCell"];
    
    [self.view addSubview:self.tableView];
    
    
    UIButton * signOutButton = [[UIButton alloc] initWithFrame:CGRectMake( 15 * SCREENH6, 400 * SCREENH6, SCREEN_WIDTH - 30 * SCREENH6, 55 * SCREENH6)];
    
    [signOutButton setTitle:@"退出登录" forState:UIControlStateNormal];
    signOutButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:17 * SCREENH6];//
    [signOutButton setBackgroundImage:[UIImage imageNamed:@"注册"] forState:UIControlStateNormal];
    signOutButton.layer.borderColor = [[UIColor blackColor] CGColor];
    //边框宽度
    signOutButton.layer.borderWidth =1.0f;
    //处理圆角
    signOutButton.layer.cornerRadius =5.0f;
    [signOutButton setTitleColor:ColorWithRGB(0xffffff) forState:UIControlStateNormal];
    [signOutButton addTarget:self action:@selector(didSignOutButton) forControlEvents:UIControlEventTouchUpInside];
    
    self.signOutButton = signOutButton;
    
    [self.view addSubview:self.signOutButton];
    
}


- (void)setupAlertVC{
    
    self.alertVC = [UIAlertController alertControllerWithTitle:@"选择照片方式" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * camerAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        _imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        
        [self presentViewController:_imagePickerController animated:YES completion:nil];
    }];
    
    UIAlertAction * albumsAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        _imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        [self presentViewController:_imagePickerController animated:YES completion:nil];
    }];
    
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [self.alertVC addAction:camerAction];
    [self.alertVC addAction:albumsAction];
    [self.alertVC addAction:cancelAction];
    
}


- (void)viewDidLayoutSubviews{
    
    [self.backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.top.bottom.mas_equalTo(self.view);
    }];
    
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 4;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (indexPath.row == 0) {
        
        self.settingCell = [tableView dequeueReusableCellWithIdentifier:@"SettingsCell" forIndexPath:indexPath];
        
        self.settingCell.subTltleLabel.text = @"修改头像";
        
        //默认头像
        if (self.iconImage) {
            self.settingCell.iconImageView.image = self.iconImage;
        }else{
            self.settingCell.iconImageView.image = [UIImage imageNamed:@"默认头像"];
        }
        
        return self.settingCell;
    }else{
        
        
        ServiceCenterTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"serviceCenterCell" forIndexPath:indexPath];
        
        if (indexPath.row == 1) {
            
            cell.titleLabel.text = @"昵称";
            cell.subTltleLabel.text = self.nameString;
            
        }else if (indexPath.row == 2){
            
            cell.titleLabel.text = @"修改密码";
            cell.subTltleLabel.text = @"";
        }else{
            
            cell.titleLabel.text = @"修改邮箱";
            cell.subTltleLabel.text = @"";
        }
        
        return cell;
        
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        
        return 75 * SCREENH6;
    }else{
        
         return 65 * SCREENH6;
    }
 
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    self.hidesBottomBarWhenPushed = YES;
    
    if (indexPath.row == 0) {
        
        [self presentViewController:self.alertVC animated:YES completion:nil];
        
    }else if (indexPath.row == 1){
        
        UpdateNameViewController * updateNameVC = [UpdateNameViewController new];
        
        updateNameVC.callBackBlock = ^(NSString *text){ // 1

            self.nameString = text;
            
            [self.tableView reloadData];
        };
        
        [self.navigationController pushViewController:updateNameVC animated:YES];
    }else if (indexPath.row == 2){
        
        UpdatePasswordViewController * updatePSVC = [UpdatePasswordViewController new];
        
        [self.navigationController pushViewController:updatePSVC animated:YES];
    }else{
        
        UpdateEmailViewController * updateEmail = [UpdateEmailViewController new];
        
        [self.navigationController pushViewController:updateEmail animated:YES];
    }
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo

{

    self.settingCell.iconImageView.image = image;
    
    if(picker.sourceType == UIImagePickerControllerSourceTypeCamera)
        
    {
        //图片存入相册
        
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
        
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    NSURLSessionDataTask *task = [[NetworkTool sharedTools] POST:@"site/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
        
        NSData *imageData =UIImageJPEGRepresentation(self.settingCell.iconImageView.image,1);
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat =@"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
        
        //上传的参数(上传图片，以文件流的格式)
        [formData appendPartWithFileData:imageData
                                    name:@"file"
                                fileName:fileName
                                mimeType:@"image/jpeg"];
        
    } progress:^(NSProgress *_Nonnull uploadProgress) {
        //打印下上传进度
    } success:^(NSURLSessionDataTask *_Nonnull task,NSDictionary * _Nullable responseObject) {
        //上传成功
        NSDictionary * dict = responseObject[@"param"];
        NSString * urlStr = dict[@"url"];
        
        NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
        
        [userDefaults setObject:urlStr forKey:@"iconUrl"];
        
        [userDefaults synchronize];
        
        NSDictionary * parametersDic = @{@"avatar":urlStr};
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        [[NetworkTool sharedTools] POST:@"user/edit-avatar" parameters:parametersDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {

            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:@"恭喜你，修改头像成功！"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      //响应事件
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            NSLog(@"%@",error);
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:@"网络连接失败！"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      //响应事件
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }];
        
        
        
    } failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
        //上传失败
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                       message:@"网络连接失败！"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction * action) {
                                                                  //响应事件
                                                                  
                                                              }];
        
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
    }];
    
}


//进入拍摄页面点击取消按钮

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker

{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}


- (void)didSignOutButton{
    
    NSUserDefaults *defatluts = [NSUserDefaults standardUserDefaults];
    
    NSDictionary *dictionary = [defatluts dictionaryRepresentation];
    
    for(NSString *key in [dictionary allKeys]){
        
        [defatluts removeObjectForKey:key];
        [defatluts synchronize];
    }
    
//    NSString *bundle = [[NSBundle mainBundle] bundleIdentifier];
//    [defatluts removePersistentDomainForName:bundle];
    
//    NSString*appDomain = [[NSBundle mainBundle] bundleIdentifier];
//    
//    [[NSUserDefaults standardUserDefaults]removePersistentDomainForName:appDomain];
    
    
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    BlackNavViewController * navVC = [[BlackNavViewController alloc] initWithRootViewController:[LoginViewController new]];
    
    appDelegate.window.rootViewController = navVC;
    
}


- (void)returnIconImage:(UpdateIconBlock)block{
    
    self.updateIconBlock = block;
}


- (void)backToAccountView{
    
    if (self.updateIconBlock != nil) {
        self.updateIconBlock(self.settingCell.iconImageView.image);
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
